package com.chinanet.utils.telnet;

import org.apache.commons.net.telnet.TelnetClient;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;

public class  IpAutomaticTelnet{  
    private TelnetClient telnet = new TelnetClient();  
    private InputStream in=null;  
    private PrintStream out=null;  
 
    
    public Map<String,Object> initTelnet(String ip, int port, String user, String password,String[] command,int type,StringBuffer sbb){
    	   Map<String,Object> map =new HashMap<>();
    	  try {  
              telnet.connect(ip, port);  
              in = telnet.getInputStream();  
              out = new PrintStream(telnet.getOutputStream());  
              int i=login(user, password,command,type,sbb);  
//              System.out.println(sbb.toString());
              map.put("flag",i);
              map.put("log", sbb.toString());
             
          } catch (Exception e) {  
              e.printStackTrace();  
              map.put("flag",9);
              map.put("log", sbb.toString());
          }
    	  return map;
    }
    
  
    /** * 登录 *  **/  
    public int login(String username,String password,String[] command,int type,StringBuffer sbb) {  
	    	
	        if(readUntil("Username",sbb)!=null){
	        	write(username);
	        	readUntil("Password:",sbb);
	        	write(password);
	        	if(readUntil("TZ-IDC2-JJ-SW.3550-DDOS>", sbb)!=null){
	        		write("en");
	        		if(readUntil("TZ-IDC2-JJ-SW.3550-DDOS#", sbb)!=null){
	        			write("conf t");
	        			if(readUntil("TZ-IDC2-JJ-SW.3550-D(config)#", sbb)!=null){
	        				
	        				if(type==1){
	        					return sendCommand(command[0],sbb,1);
	        				}else if(type==2){
	        					return sendCommand(command[1],sbb,2);
	        				}else{
	        					int flag=sendCommand(command[0],sbb,1);
	        					if(flag==0){
	        						return sendCommand(command[1],sbb,2);
	        					}else{
	        						return flag;
	        					}
	        				}
	        				
	        			}else{
	        				//conf t 返回结构有误
	        				return 4;
	        			}
	        		}else{
	        			//输入EN返回结果有误
	        			return 3;
	        		}
	        	}else{
	        		//用户名或密码错误
	        		return 2;
	        	}
	        }else{
	        	//telnet连接失败
	        	return 1;  
	      } 
    } 
    
    
    /**
     * 
     * @param command
     * @param sbb
     * @param type 1:add;2:delete
     * @return
     */
    public int sendCommand(String command,StringBuffer sbb,int type){
    	
			write(command);
			if(type==1){
				if(readUntilt("%Inconsistent address and mask\r\nTZ-IDC2-JJ-SW.3550-D(config)#", sbb)!=1){
					//添加路由失败
					return 5;
				}else{
					//添加或删除路由成功
					return 0;
				}
			}else{
					if(readUntilt("%No matching route to delete\r\nTZ-IDC2-JJ-SW.3550-D(config)#", sbb)!=1){
						//删除路由失败,未找到该路由
						return 7;
					}else{
						//添加或删除路由成功
						return 0;
					}
			
				}
			
		
    }
    
    
    
    
    
  
    /** * 读取分析结果 * * @param pattern * @return */  
    public String readUntil(String pattern,StringBuffer sbb) {  
        try {
            char lastChar = pattern.charAt(pattern.length() - 1);  
            StringBuffer sb = new StringBuffer();  
            char ch = (char) in.read();  
            while (true) {  
                sb.append(ch); 
                sbb.append(ch);
            	
                if (ch == lastChar) {  
                
                    if (sb.toString().endsWith(pattern)) { 
                        return sb.toString();  
                    }
                } 
              
                ch = (char) in.read();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }   
    
    public int readUntilt(String pattern,StringBuffer sbb) {  
        try {
            char lastChar = pattern.charAt(pattern.length() - 1);  
            StringBuffer sb = new StringBuffer();  
            char ch = (char) in.read();  
            while (true) {  
                sb.append(ch); 
                sbb.append(ch);
                if (ch == lastChar) {  
                    if (sb.toString().endsWith(pattern)) { 
                        return 0;  
                    }else{
                    	return 1;  
                    }
                } 
              
                ch = (char) in.read();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return 1;  
    }   
    
   
  
  
    /** * 写操作 * * @param value */  
    public void write(String value) {  
        try {  
            out.println(value);  
            out.flush();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    
   
    
  
    /** * 关闭连接 */  
    public void disconnect() {  
        try {  
            telnet.disconnect();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }
    
	
  /**
   * 
   * @param ipAddress
   * @param subnetMask
   * @param datetime
   * @param type 1:添加；2:删除;3:添加和删除
   * @return
   */
	public Map<String,Object> init(String ipAddress,String subnetMask,String datetime,int type){
	    StringBuffer sbb = new StringBuffer();    
		Map<String,Object> map = new HashMap<>();
		String ip = "60.189.12.25";  
        int port = 23;  
        String user = "wyfzxt";  
        String password = "tz@88680988";  
        IpAutomaticTelnet telnet = new IpAutomaticTelnet(); 
       
        
        map.put("flag", "1");
        try{
        	
        	String[] command =new String[2];
        	 command[0]="ip route  "+ipAddress.trim()+"  "+subnetMask.trim()+" Null0 tag 100 name "+datetime.trim();
        	 command[1]="no ip route  "+ipAddress.trim()+"  "+subnetMask.trim()+" Null0 tag 100 name "+datetime.trim();
        	 
        	Map<String,Object> rmap = telnet.initTelnet(ip, port, user, password,command,type,sbb);
        	int loginFlag = Integer.parseInt(String.valueOf(rmap.get("flag")));
        	System.out.println(loginFlag);
			        if(loginFlag==0){
			        	map.put("flag","0");
			        	map.put("msg", "操作成功");
			        }else if(loginFlag==1){
			        	map.put("msg", "telnet连接失败");
			        }else if(loginFlag==2){
			        	map.put("msg", "用户名或密码错误");
			        }else if(loginFlag==3){
			        	map.put("msg", "输入EN返回结果有误");
			        }else if(loginFlag==4){
			        	map.put("msg", "conf t 返回结构有误");
			        }else if(loginFlag==5){
			        	map.put("msg", "添加路由失败,命令格式错误");
			        }else if(loginFlag==6){
			        	map.put("msg", "删除路由失败");
			        }else if(loginFlag==7){
			        	map.put("msg", "删除路由失败,未找到该路由");
			        }else if(loginFlag==8){
			        	map.put("msg", "删除路由失败,命令格式错误");
			        }else{
			        	map.put("msg", "服务器报错-1");
			        }
			        map.put("log", String.valueOf(rmap.get("log")).replaceAll("\b",""));
        }catch(Exception e){ 
        	e.printStackTrace();
        	map.put("msg", "服务器报错");
        	map.put("log", "服务器报错-1");
        }finally{
        	telnet.disconnect();
        	
        }
		return map;
		
	}
	

    
  

    


	
  

    
    
   
}  


